/**
 * Writed by yura and mak
 */

package wz.legend.handlers.steps;

import org.apache.log4j.Logger;

import wz.legend.Context;
import wz.legend.HttpContext;
import wz.legend.Status;
import wz.legend.handlers.info.InfoConstants;
import wz.legend.util.ParseUtils;
import wz.legend.util.ScriptStarter;
import wz.legend.util.Utils;


public class CheckAreaStep extends AbstractStep {
    private static final Logger LOG = Logger.getLogger(CheckAreaStep.class);

    private String areaName = "";

    public void execute(Context context) {
        LOG.debug("CheckAreaStep START " + areaName);
        context.getScriptStater().doScript("steps.location");
        state = State.START;
    }

    public void handle(HttpContext httpContext, Context context) {
        try {
            if (httpContext != null) {
                String uri = httpContext.getRequest().getRequestLine().getUri();
                if (uri.endsWith(ParseUtils.AREA_PHP + "?exit=1")
                        && state == State.START) {
                    String currentAreaName = (String) context
                            .getProperty(InfoConstants.AREA_NAME);
                    if (areaName.toLowerCase().equals(
                            currentAreaName.toLowerCase())) {
                        LOG.debug("CheckAreaStep STOPED");
                        state = State.STOPED;
                    } else {
                        LOG.debug("CheckAreaStep wrong area = "
                                + currentAreaName);
                        context.setStatus(Status.INACTIVE);
                        reset();
                    }
                }
            }
        } catch (Exception e) {
            LOG.error(e, e);
            throw new RuntimeException(e);
        }
    }

    public String getAreaName() {
        return areaName;
    }

    public void setAreaName(String areaName) {
        this.areaName = areaName;
    }

}
